<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    ul {
      list-style-type: none;
      display: flex;
      flex-wrap: wrap;
    }

    li {
      width: 25%;
      background-color: pink;
    }
  </style>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for="film in films" :key="film.filmId">
        <img :src="film.poster" alt="">
        <h2>{{film.name}}</h2>
      </li>
    </ul>
  </div>

  <script src="./vue.js"></script>
  <script src="./axios.js"></script>
  <script>
    const request = axios.create({
      baseURL: 'https://m.maizuo.com',
      headers: { // 设置请求头
        "X-Client-Info": '{"a":"3000","ch":"1002","v":"5.0.4","e":"1597720815568988677439489","bc":"110100"}',
        "X-Host": "mall.film-ticket.film.list"
      }
    })

    // 添加一个请求的拦截
    request.interceptors.request.use(function (config) {
        // 发送之前可以做些xxxx
        console.log("拦截啦")
        const token = 'hwfhe43987493rifur3ofde';
        config.headers['access_token'] = token;
        console.log(config)
        return config; // 放行 如果没有 return 所有的用axios的ajax请求都发送不过去
      }, function (error) {
        // 请求错误的拦截 return 出去 没有的 promise一直pending状态 catch一直无法触发
        return Promise.reject(error);
      });

    // 响应拦截
    request.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        console.log("后端返回数据了")
        /* 
        {
          code: 401,
          msg:"token过期了"
        }
         */
         if(response.data.code === 401){
          //  token过期了
          // 跳转到登录页
         }
        response.aaa="嘿嘿嘿";
        return response;
      }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      });
    const vm = new Vue({
      el: "#app",
      data: {
        films: []
      },
      created() {
        this.fetchFilmData()
      },
      methods: {
        fetchFilmData() {
          // 封装了 请求 数据函数
          request.get('/gateway', {
            params: {
              cityId: '110100',
              pageNum: '1',
              pageSize: '10',
              type: '1',
              k: '2183988'
            }
          }).then(res => {
            console.log(res)
            if (res.data.status === 0) {
              this.films = res.data.data.films
            }
          })
        }
      }
    })
    // cors 跨站资源共享 后端 设置 接口访问 白名单
  </script>
</body>

</html>
